#!/usr/bin/env node

import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import { createWriteStream } from 'fs'
import archiver from 'archiver'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const projectRoot = path.resolve(__dirname, '..')

const distDir = path.join(projectRoot, 'dist')
const unpackedDir = path.join(distDir, 'unpacked')
const zipPath = path.join(distDir, 'ChromeExt.zip')

console.log('🚀 开始构建Chrome扩展ZIP包...')

// 1. 检查dist目录是否存在
if (!fs.existsSync(distDir)) {
  console.error('❌ dist目录不存在，请先运行 pnpm build')
  process.exit(1)
}

// 2. 创建unpacked目录
console.log('📁 创建unpacked目录...')
if (fs.existsSync(unpackedDir)) {
  fs.rmSync(unpackedDir, { recursive: true, force: true })
}
fs.mkdirSync(unpackedDir, { recursive: true })

// 3. 复制dist内容到unpacked目录
console.log('📂 复制文件到unpacked目录...')
function copyDirectory(src, dest) {
  const entries = fs.readdirSync(src, { withFileTypes: true })

  for (const entry of entries) {
    const srcPath = path.join(src, entry.name)
    const destPath = path.join(dest, entry.name)

    if (entry.isDirectory()) {
      fs.mkdirSync(destPath, { recursive: true })
      copyDirectory(srcPath, destPath)
    } else {
      fs.copyFileSync(srcPath, destPath)
    }
  }
}

// 复制除了可能存在的旧unpacked和zip文件外的所有内容
const entries = fs.readdirSync(distDir, { withFileTypes: true })
for (const entry of entries) {
  if (entry.name !== 'unpacked' && entry.name !== 'ChromeExt.zip') {
    const srcPath = path.join(distDir, entry.name)
    const destPath = path.join(unpackedDir, entry.name)

    if (entry.isDirectory()) {
      fs.mkdirSync(destPath, { recursive: true })
      copyDirectory(srcPath, destPath)
    } else {
      fs.copyFileSync(srcPath, destPath)
    }
  }
}

// 4. 验证关键文件存在
const manifestPath = path.join(unpackedDir, 'manifest.json')
if (!fs.existsSync(manifestPath)) {
  console.error('❌ manifest.json文件不存在')
  process.exit(1)
}

// 5. 创建ZIP文件
console.log('📦 创建ZIP包...')
if (fs.existsSync(zipPath)) {
  fs.unlinkSync(zipPath)
}

const output = createWriteStream(zipPath)
const archive = archiver('zip', {
  zlib: { level: 9 } // 最大压缩级别
})

output.on('close', () => {
  const sizeInMB = (archive.pointer() / 1024 / 1024).toFixed(2)
  console.log(`✅ ZIP包创建成功: ${sizeInMB} MB`)
  console.log(`📍 位置: ${zipPath}`)

  // 验证文件大小（Chrome Web Store限制）
  if (archive.pointer() > 128 * 1024 * 1024) { // 128MB
    console.warn('⚠️  警告: ZIP包大小超过128MB，可能不符合Chrome Web Store要求')
  }

  console.log('\n🎉 构建完成!')
  console.log(`📁 unpacked目录: ${unpackedDir}`)
  console.log(`📦 ZIP文件: ${zipPath}`)
})

archive.on('error', (err) => {
  console.error('❌ 创建ZIP包失败:', err)
  process.exit(1)
})

archive.pipe(output)

// 添加unpacked目录中的所有文件到ZIP
archive.directory(unpackedDir, false)

archive.finalize()